package com.temple.service.card.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.comon.core.domain.result.R;
import com.comon.core.enums.ResultCode;
import com.temple.config.UserClientService;
import com.temple.mapper.CardMapper;
import com.temple.mapper.RemarkMapper;
import com.temple.mapper.circleMapper;
import com.temple.model.card.CardInfo;
import com.temple.model.card.DTO.CardInfoDTO;
import com.temple.model.card.DTO.CardNewInfo;
import com.temple.model.card.DTO.SelfTieZiDTO;
import com.temple.model.card.VO.SelfPictureVO;
import com.temple.model.card.VO.SelfTieZiVO;
import com.temple.model.circle.CircleInfo;
import com.temple.model.remark.Remark;
import com.temple.model.remark.Vo.RemarkVO;
import com.temple.service.CircleService;
import com.temple.service.card.CardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created with Intellij IDEA.
 * Description;
 * User:TQ02
 * Data:2024-09-12
 * Time:12:17
 * Text：
 */
@Service
public class CardServiceImpl  extends ServiceImpl<CardMapper, CardInfo> implements  CardService {
    @Autowired
    CardMapper cardMapper;
    @Autowired
    private UserClientService userClientService;
    @Autowired
    circleMapper circleMapper;
    @Autowired
    RemarkMapper remarkMapper;

    private final String Id = "http://120.46.91.1:9000/test/";

    @Override
    public R<?> CreateTieZi(Long uid, CardInfoDTO cardInfoDTO, List<MultipartFile> files) {
        CardInfo cardInfo = new CardInfo();
        cardInfo.setCardTitle(cardInfoDTO.getCardTitle());
        cardInfo.setCardContent(cardInfoDTO.getCardContent());
        cardInfo.setCardUid(uid);
        cardInfo.setCardPlnumber(0);
        cardInfo.setCardCirid(cardInfoDTO.getCardCirid());
        StringBuilder str = new StringBuilder();
        if(files == null|| files.isEmpty()){
            str.append("NULL");
        }else{
            for(MultipartFile file:files){
                str.append(Id+file.getOriginalFilename()+"##");
                userClientService.setFile(file);
            }
        }
        cardInfo.setCardPhoto(str.toString());
        cardMapper.insert(cardInfo);
        return R.ok();
    }
    @Override
    public R<?> publicPicture(Long uid,String cardCirid, List<MultipartFile> files) {
        CardInfo cardInfo = new CardInfo();
        cardInfo.setCardUid(uid);
        // 去掉引号和空格
        cardCirid = cardCirid.replace("\"", "").trim();
        cardInfo.setCardCirid(Integer.valueOf(cardCirid));
        StringBuilder str = new StringBuilder();
        for(MultipartFile file:files){
            str.append(Id+file.getOriginalFilename()+"##");
            userClientService.setFile(file);
        }
        cardInfo.setCardPhoto(str.toString());
        cardMapper.insert(cardInfo);
        return R.ok();
    }



    @Override
    public R<?> getNewTieZi(int start) {
        // 创建分页对象
        Page<CardInfo> page = new Page<>(start,5);

        // 创建查询条件
        LambdaQueryWrapper<CardInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.isNotNull(CardInfo::getCardTitle);
        lambdaQueryWrapper.eq(CardInfo::getParentId,0);
        // 根据插入时间降序排列
        lambdaQueryWrapper.orderByDesc(CardInfo::getCreateTime); // 假设有一个插入时间字段


        // 执行分页查询
        IPage<CardInfo> result = cardMapper.selectPage(page, lambdaQueryWrapper);

        // 检查结果是否为空
        if (result.getRecords().isEmpty()) {
            return R.fail(ResultCode.FAILED_NOT_EXISTS);
        }
        // 将 CardInfo 转换为 CardNewInfo
        List<CardNewInfo> list = result.getRecords().stream()
                .map(cardInfo -> {
                    CardNewInfo cardNewInfo = new CardNewInfo();
                    cardNewInfo.setCardId(cardInfo.getCardId());
                    cardNewInfo.setCardTitle(cardInfo.getCardTitle());
                    cardNewInfo.setCardContent(cardInfo.getCardContent());
                    cardNewInfo.setCardPhoto(cardInfo.getCardPhoto());
                    cardNewInfo.setCardUid(cardInfo.getCardUid());
                    cardNewInfo.setCardPlnumber(cardInfo.getCardPlnumber());
                    cardNewInfo.setCardCirid(cardInfo.getCardCirid());
                    cardNewInfo.setCreateTime(cardInfo.getCreateTime());
                    cardNewInfo.setUpdateTime(cardInfo.getUpdateTime());
                    return cardNewInfo;
                })
                .collect(Collectors.toList());
        for (CardNewInfo cardNewInfo : list) {
            Long uId = cardNewInfo.getCardUid();
            int templeId = cardNewInfo.getCardCirid();

            // 获取 CircleInfo
            CircleInfo circleInfo = circleMapper.selectOne(
                    new LambdaQueryWrapper<CircleInfo>().eq(CircleInfo::getCirId, templeId)
            );

            // 获取用户名称
            String name = userClientService.getUserById(uId);

            // 设置到 CardNewInfo
            cardNewInfo.setCardUName(name);
            if (circleInfo != null) {
                cardNewInfo.setTempleName(circleInfo.getCircleName());
            } else {
                cardNewInfo.setTempleName("未知"); // 或者其他默认值
            }
        }
        return R.ok(list);
    }

    /**
     * @description: 获取殿堂的数据
     * @param
     * @return: null 数据的总数，当前页表的数目
    **/
    @Override
    public R<?> getSelfTieZi(SelfTieZiDTO selfTieZiDTO) {
        // 创建分页对象
        Page<CardInfo> page = new Page<>(selfTieZiDTO.getCurrentPage(),selfTieZiDTO.getPageSize());

        // 创建查询条件
        LambdaQueryWrapper<CardInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(CardInfo::getCardCirid,selfTieZiDTO.getTempleId()).isNotNull(CardInfo::getCardTitle);
        lambdaQueryWrapper.eq(CardInfo::getParentId,0);
        // 根据插入时间降序排列
        lambdaQueryWrapper.orderByDesc(CardInfo::getCreateTime); // 假设有一个插入时间字段

        // 执行分页查询
        IPage<CardInfo> result = cardMapper.selectPage(page, lambdaQueryWrapper);

        //查询数据的总数
        Long count = cardMapper.selectCount(lambdaQueryWrapper);

        // 将 CardInfo 转换为 CardNewInfo
        List<SelfTieZiVO> list = result.getRecords().stream()
                .map(cardInfo -> {
                    String name = userClientService.getUserById(cardInfo.getCardUid());
                    SelfTieZiVO selfTieZiVO = new SelfTieZiVO();
                    selfTieZiVO.setCardId(cardInfo.getCardId());
                    selfTieZiVO.setTitle(cardInfo.getCardTitle());
                    selfTieZiVO.setContent(cardInfo.getCardContent());
                    selfTieZiVO.setPhoto(cardInfo.getCardPhoto());
                    selfTieZiVO.setCreateTime(cardInfo.getCreateTime());
                    selfTieZiVO.setUpdateTime(cardInfo.getUpdateTime());
                    selfTieZiVO.setName(name);
                    selfTieZiVO.setTotal(count);
                    return selfTieZiVO;
                })
                .collect(Collectors.toList());

        return R.ok(list);
    }
    @Override
    public R<?> getSelfPicture(SelfTieZiDTO selfTieZiDTO) {
        // 创建分页对象
        Page<CardInfo> page = new Page<>(selfTieZiDTO.getCurrentPage(),selfTieZiDTO.getPageSize());

        // 创建查询条件
        LambdaQueryWrapper<CardInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(CardInfo::getCardCirid,selfTieZiDTO.getTempleId())
                .isNull(CardInfo::getCardTitle);
        // 根据插入时间降序排列
        lambdaQueryWrapper.orderByDesc(CardInfo::getCreateTime); // 假设有一个插入时间字段

        // 执行分页查询
        IPage<CardInfo> result = cardMapper.selectPage(page, lambdaQueryWrapper);

        //查询数据的总数
        Long count = cardMapper.countDistinctCreateTimeByTempleId(selfTieZiDTO.getTempleId());
        StringBuilder str = new StringBuilder();

        // 将 CardInfo 转换为 CardNewInfo
        List<SelfPictureVO> list = result.getRecords().stream()
                .map(cardInfo -> {
                    String name = userClientService.getUserById(cardInfo.getCardUid());
                    SelfPictureVO selfTieZiVO = new SelfPictureVO();
                    selfTieZiVO.setUID(cardInfo.getCardUid());
                    selfTieZiVO.setPhoto(cardInfo.getCardPhoto());
                    selfTieZiVO.setName(name);
                    // 获取 cardInfo 的 createTime，假设它是 LocalDateTime 类型
                    LocalDateTime createTime = cardInfo.getCreateTime();
                    // 转换为 LocalDate
                    LocalDate localDate = createTime.toLocalDate();
                    selfTieZiVO.setCreateTime(localDate);
                    selfTieZiVO.setTotal(count);
                    return selfTieZiVO;
                })
                .collect(Collectors.toList());
        Map<LocalDate,List<SelfPictureVO>> list2 = new HashMap<>();
        for(SelfPictureVO selfPictureVO:list){
            LocalDate time = selfPictureVO.getCreateTime();
            // Check if the map already contains the key
            if (!list2.containsKey(time)) {
                // If not, initialize a new list
                list2.put(time, new ArrayList<>());
            }
            // Add the SelfPictureVO to the appropriate list
            list2.get(time).add(selfPictureVO);
        }

        return R.ok(list2);
    }

    @Override
    public R<?> getTieZiInfo(int cardId, Long Uid) {
        // 创建查询条件---获得当前的帖子
        LambdaQueryWrapper<CardInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(CardInfo::getCardId,cardId);
        CardInfo circleInfo = cardMapper.selectOne(lambdaQueryWrapper);

        //获得当前帖子下，其他回复的帖子
        LambdaQueryWrapper<CardInfo> lambdaQueryWrapper2 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper2.eq(CardInfo::getParentId,cardId);
        List<CardInfo> circleInfolist = cardMapper.selectList(lambdaQueryWrapper2);

        //获得评论，当前所有帖子包括回帖的评论
        LambdaQueryWrapper<Remark> lambdaQueryWrapper3 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper3.eq(Remark::getAId,cardId).or().eq(Remark::getParentId,cardId);
        List<Remark> remarkList = remarkMapper.selectList(lambdaQueryWrapper3);
        Map<Integer, List<RemarkVO>> map = new HashMap<>();
        for(Remark remark:remarkList){
            if(!map.containsKey(remark.getAId())){
                map.put(remark.getAId(),new ArrayList<>());
            }
            RemarkVO remarkVO =new RemarkVO(remark);
            map.get(remark.getAId()).add(remarkVO);
        }

        Map<String,Object> map1 = new HashMap<>();
        map1.put("circleInfo",circleInfo);
        map1.put("circleInfoList",circleInfolist);
        map1.put("remark",map);
        return R.ok(map1);
    }


}
